import { storeOptions } from '@/config/store.config'

const options = storeOptions
// *生成数据格式
const generateData = (value: any, timeout: number) => {
  const obj = {
    expire: new Date().getTime() + timeout,
    value,
  }
  return JSON.stringify(obj)
}

/**
 * @description: 存储数据
 * @param key {String} 存储的key
 * @param initialValue {Ref} 存储的value
 * @returns { {get,set, remove}} value
 */
export function useLS(key = '', initialValue = '') {
  const lsKey = `${options.key}${key}`

  const remove = () => {
    localStorage.removeItem(lsKey)
  }
  const get = (key?: string) => {
    let data: string | null = ''
    if (key) {
      data = localStorage.getItem(`${options.key}${key}`)
    } else {
      data = localStorage.getItem(lsKey)
    }

    try {
      if (data) {
        const obj = JSON.parse(data)
        // *过期数据 销毁
        if (obj.expire > new Date().getTime()) {
          return obj.value
        } else {
          remove()
          return null
        }
      } else {
        // *无数据
        return null
      }
    } catch (e) {
      console.log('🚨  -> get  -> err', e)
      remove()
      return null
    }
  }

  const set = (value, timeout = options.timeout) => {
    options.logger &&
      console.log('👉  -> watch localStorage', key, value, generateData(value, timeout))
    localStorage.setItem(lsKey, generateData(value, timeout))
  }

  initialValue && set(initialValue)

  return { get, set, remove }
}
